//
//  SLAddressPickerView.m
//  SulitLoanDemo
//
//  Created by 虞嘉伟 on 2025/2/22.
//

#import "SLAddressPickerView.h"
#import <YYKit.h>
#import <Masonry.h>



@interface SLAddressPickerViewItem : UIView
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UIImageView *arrow;
@property (nonatomic, assign) BOOL isFill;
@end
@implementation SLAddressPickerViewItem
- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        _titleLabel = [UILabel new];
        _titleLabel.text = @"Manila metropolitan area";
        _titleLabel.font = aspectDefaultFont(18);
        _titleLabel.textColor = UIColorHex(#1B1B1B);
        [self addSubview:_titleLabel];
        [_titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self).inset(35);
            make.top.bottom.equalTo(self);
        }];
        _arrow = [UIImageView new];
        _arrow.image = [UIImage imageNamed:@"btn_more_gray"];
        _arrow.contentMode = UIViewContentModeScaleAspectFit;
        [self addSubview:_arrow];
        [_arrow mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_titleLabel.mas_right);
            make.right.equalTo(self).inset(36);
            make.width.height.mas_equalTo(22);
            make.centerY.equalTo(self);
        }];
    }
    return self;
}
@end

@interface SLAddressPickerViewHeader : UITableViewHeaderFooterView
@property (nonatomic, strong) UILabel *titleLabel;
@end
@implementation SLAddressPickerViewHeader
- (instancetype)initWithReuseIdentifier:(NSString *)reuseIdentifier {
    if (self = [super initWithReuseIdentifier:reuseIdentifier]) {
        self.backgroundColor = UIColor.clearColor;
        self.contentView.backgroundColor = UIColor.clearColor;
        _titleLabel = [UILabel new];
        _titleLabel.text = @"Select the region/city";
        _titleLabel.font = aspectDefaultFont(18);
        _titleLabel.textColor = UIColorHex(#1B1B1B);
        [self.contentView addSubview:_titleLabel];
        [_titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self.contentView).inset(35);
            make.top.bottom.equalTo(self.contentView);
        }];
    }
    return self;
}
@end
@interface SLAddressPickerViewCell : UITableViewCell
@property (nonatomic, strong) UILabel *titleLabel;
@end
@implementation SLAddressPickerViewCell
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        self.backgroundColor = UIColor.clearColor;
        self.contentView.backgroundColor = UIColor.clearColor;
        _titleLabel = [UILabel new];
        _titleLabel.text = @"A";
        _titleLabel.font = aspectDefaultFont(14);
        _titleLabel.textColor = UIColorHex(#999999);
        [self.contentView addSubview:_titleLabel];
        [_titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self.contentView).inset(35);
            make.top.bottom.equalTo(self.contentView);
        }];
    }
    return self;
}
@end













@interface SLAddressPickerView ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UIStackView *stackView;
@property (nonatomic, strong) UIView *lineView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, copy  ) NSArray<NSDictionary *> *data;
@property (nonatomic, copy  ) NSArray<NSDictionary *> *show;
@property (nonatomic, copy  ) NSMutableArray<NSNumber *> *select;
@end

@implementation SLAddressPickerView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        _select = [NSMutableArray array];
        [self.customView addSubview:self.stackView];
        [self.stackView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self.customView);
            make.top.equalTo(self.customView).offset(5);
        }];
        
        [self.customView addSubview:self.lineView];
        [self.lineView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self.customView).inset(-1);
            make.height.mas_equalTo(10);
            make.top.equalTo(self.stackView.mas_bottom).offset(5);
        }];
        
        [self.customView addSubview:self.tableView];
        [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self.customView);
            make.top.equalTo(self.lineView.mas_bottom);
            make.bottom.equalTo(self.customView);
            make.height.mas_equalTo(236);
        }];
        
        [self.customView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self.pannel);
            make.top.equalTo(self.decorate.mas_bottom);
            make.bottom.equalTo(self.pannel);
        }];
        [AddressRequestProvider requestAddressWithSuccess:^(NSArray * _Nonnull arr) {
            self.data = arr;
            self.show = arr;
            self.addressData = arr;
            [self reloadData];
        } failure:^(YTKRequest * _Nonnull request) {
            
        }];
    }
    return self;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 15*2+22;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 18+15;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.show.count;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"SLAddressPickerViewHeader"];
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return nil;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SLAddressPickerViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SLAddressPickerViewCell" forIndexPath:indexPath];
    NSDictionary *dict = self.show[indexPath.row];
    NSString *title = dict[@"veins"];
    cell.titleLabel.text = title;
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
//    NSDictionary *dict = self.show[indexPath.row];
//    NSArray *sensitive = dict[@"sensitive"];
//    if (sensitive.count) {
//        self.show = sensitive;
//        [tableView reloadData];
//    }
    if (_select.count == self.stackView.arrangedSubviews.count) {
        // 最后一列
        [_select removeLastObject];
    }
    [_select addObject:@(indexPath.row)];
//    SLAddressPickerViewItem *item = self.stackView.arrangedSubviews[_select.count-1];
//    item.isFill = YES;
//    item.titleLabel.text = dict[@"veins"];
    
    [self reloadData];
}

- (void)setSelect:(NSMutableArray *)select {
    if (select.count) {
        _select = select;
    }
}

/// 地址深度
- (NSInteger)addressDeep {
    int count = 0;
    NSArray *arr = self.data;
    while (arr.count) {
        count++;
        NSDictionary *dict = arr.firstObject;
        arr = dict[@"sensitive"];
    }
    return count;
}
- (void)reloadData {
    NSArray<SLAddressPickerViewItem *> *views = self.stackView.subviews;
    NSString *title = @"Please Select";
    NSInteger deep = [self addressDeep];
    NSArray *arr = self.data;
    for (int i=0; i<deep; i++) {
        if (i<self.select.count) {
            /// 有选择过的
            // 地址选择的下标
            NSInteger index = self.select[i].intValue;
            // 地址选择的名称
            title = arr[index][@"veins"];
            if (i < deep-1) {
                // 地址选择的展示列表
                arr = arr[index][@"sensitive"];
            }
        } else {
            title = @"Please Select";
        }
        views[i].titleLabel.text = title;
    }
    self.show = arr;
    [self.tableView reloadData];
}

- (void)setAddressData:(NSArray *)addressData {
    _addressData = addressData;
    [self.stackView removeAllSubviews];
    NSInteger deep = [self addressDeep];
    for (int i=0; i<deep; i++) {
        SLAddressPickerViewItem *item = [SLAddressPickerViewItem new];
        item.tag = i;
        [self.stackView addArrangedSubview:item];
        [item jk_addTapActionWithBlock:^(UIGestureRecognizer *gestureRecoginzer) {
            // 清除被点击的item以后得视图标记
            NSMutableArray *temp = [NSMutableArray array];
            for (int i=0; i<item.tag+1; i++) {
                if (i < self.select.count) {
                    [temp addObject:self.select[i]];
                }
            }
            self.select = temp;
            [self reloadData];
        }];
        
        [item mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(32);
        }];
    }
    
    //[self.tableView reloadData];
}

//- (void)setAddressData:(NSArray *)addressData {
//    _addressData = addressData;
//    [self.stackView removeAllSubviews];
//    int count = 0;
//    NSArray *arr = self.data;
//    while (arr.count) {
//        count++;
//        NSDictionary *dict = arr.firstObject;
//        arr = dict[@"sensitive"];
//    }
////    NSArray *arr1 = self.data;
//    for (int i=0; i<count; i++) {
//        SLAddressPickerViewItem *item = [SLAddressPickerViewItem new];
//        item.tag = i;
////        NSString *title = @"Please Select";
////        if (i < self.select.count) {
////            title = arr1[self.select[i].intValue][@"veins"];
////            arr1 = arr1[self.select[i].intValue][@"sensitive"];
////        }
////        //item.titleLabel.text =
//        
//        [self.stackView addArrangedSubview:item];
//        [item jk_addTapActionWithBlock:^(UIGestureRecognizer *gestureRecoginzer) {
//            // 清除被点击的item以后得视图标记
//            for (int i = 0; i < self.stackView.arrangedSubviews.count; i++) {
//                SLAddressPickerViewItem *it = self.stackView.arrangedSubviews[i];
//                if (i > item.tag) {
//                    it.isFill = NO;
//                    it.titleLabel.text = @"Please Select";
//                }
//            }
//            NSArray *arr = self.data;
//            if (item.tag > self.select.count) {
//                return;
//            }
//            NSArray *newSelect = [self.select subarrayWithRange:NSMakeRange(0, item.tag)];
//            for (NSNumber *n in newSelect) {
//                NSDictionary *dict = arr[n.intValue];
//                arr = dict[@"sensitive"];
//            }
//            self.show = arr;
//            [self.tableView reloadData];
//            
//        }];
//        
//        [item mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.height.mas_equalTo(32);
//        }];
//    }
//    
//    [self.tableView reloadData];
//}

// override
- (void)confirmButtonAction:(UIButton *)button {
    if (_select.count != self.stackView.arrangedSubviews.count) {
        return;
    }
    NSMutableArray *list = [NSMutableArray array];
    NSArray *arr = self.data;
    for (NSNumber *n in _select) {
        NSDictionary *dict = arr[n.intValue];
        NSString *veins = dict[@"veins"];
        NSString *didn = dict[@"didn"];
        arr = dict[@"sensitive"];
        [list addObject:dict];
        NSLog(@"----地址: %@ [%@]", veins, didn);
    }
    
    !self.confirmButtonCallback ?: self.confirmButtonCallback(list);
    !self.addressConfirmButtonCallback ?: self.addressConfirmButtonCallback(list, self.select);
    [super confirmButtonAction:button];
}





- (UIStackView *)stackView {
    if (!_stackView) {
        _stackView = [UIStackView new];
        _stackView.axis = UILayoutConstraintAxisVertical;
    }
    return _stackView;
}
- (UIView *)lineView {
    if (!_lineView) {
        _lineView = [UIView new];
        _lineView.backgroundColor = UIColorHex(#FDC5E0);
        _lineView.layer.borderColor = UIColorHex(#1B1B1B).CGColor;
        _lineView.layer.borderWidth = 1;
    }
    return _lineView;
}
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = UIColor.clearColor;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerClass:SLAddressPickerViewHeader.class forHeaderFooterViewReuseIdentifier:@"SLAddressPickerViewHeader"];
        [_tableView registerClass:SLAddressPickerViewCell.class forCellReuseIdentifier:@"SLAddressPickerViewCell"];
        _tableView.sectionHeaderHeight = 0.01;
        if (@available(iOS 15.0, *)) {
            _tableView.sectionHeaderTopPadding = 0.01;
        }
    }
    return _tableView;
}

@end






@implementation SLAddressPickerView (Fast)

+ (instancetype)showAddressChooseWithDefaultAddress:(NSMutableArray *)defaultAddress confirmCallback:(void(^)(NSMutableArray<NSDictionary *> *address, NSMutableArray<NSNumber *> *indexs))block {
    
    SLAddressPickerView *alert = [SLAddressPickerView new];
    alert.titleLabel.text = @"Address Selection";
    //alert.addressData = arr;
    alert.select = defaultAddress;
    [alert reloadData];
    alert.addressConfirmButtonCallback = block;
    [UIApplication.sharedApplication.windows.firstObject addSubview:alert];
    [alert mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(alert.superview);
    }];
    
    return alert;
}
+ (instancetype)showAddressChooseWithData:(NSArray *)arr confirmCallback:(void(^)(NSMutableArray<NSDictionary *> *select))block {
    
    SLAddressPickerView *alert = [SLAddressPickerView new];
    alert.titleLabel.text = @"Address Selection";
    alert.addressData = arr;
    alert.confirmButtonCallback = block;
    [UIApplication.sharedApplication.windows.firstObject addSubview:alert];
    [alert mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(alert.superview);
    }];
    
    return alert;
}

@end

